package pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes;

import java.util.Calendar;

import org.unigrids.services.atomic.types.GridFileType;

import de.fzj.unicore.uas.client.StorageClient;
import de.fzj.unicore.wsrflite.xmlbeans.BaseFault;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.utils.TreeUtils;

public class CatalogNode extends BelowStorageNode {

	public static final String CLOSED_ICON_NAME = "icons/closed_folder.png";
	private boolean hasSiblings = false;
	private boolean opened = false;
	private MultiplyCatalogNode multiplyCatalogNode;
	private Calendar lastModified;
	private String owner;
	
	public String getName() {
		int index = getPath().lastIndexOf("/");
		if (index != -1) {
			return getPath().substring(index + 1);
		}
		return "No name";
	}
	
	public boolean listCatalog() {
		StorageClient client = this.getStorage().getClient();
		try {
			GridFileType[] files = client.listDirectory(this.getPath());
			this.setChildren(null);
			TreeUtils.addGridFileTypes(this, files);
			return this.getChildren().size() > 0;
		} catch (BaseFault e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public boolean hasSiblings() {
		return hasSiblings;
	}
	
	public void setHasSiblings(boolean val) {
		hasSiblings = val;
	}

	public MultiplyCatalogNode getMultiplyCatalogNode() {
		return multiplyCatalogNode;
	}

	public void setMultiplyCatalogNode(MultiplyCatalogNode multiplyCatalogNode) {
		this.multiplyCatalogNode = multiplyCatalogNode;
	}

	public boolean isOpened() {
		return opened;
	}

	public void setOpened(boolean opened) {
		this.opened = opened;
	}
	
	@Override
	public CatalogNode clone(Node nodeParent) {
		CatalogNode catalogNode = new CatalogNode();
		catalogNode.setParent(nodeParent);
		catalogNode.setPath(this.getPath());
		catalogNode.setHasSiblings(hasSiblings);
		catalogNode.setOpened(opened);
		
		for (Node n : this.getChildren()) {
			Node n2 = n.clone(catalogNode);
			catalogNode.add(n2);
		}
		
		return catalogNode;
	}

	public void setLastModified(Calendar lastModified) {
		this.lastModified = lastModified;
	}
	
	public Calendar getLastModified() {
		return lastModified;
	}
	
	public String getOwner() {
		return owner;
	}

	public void setOwner(String owner) {
		this.owner = owner;
	}
	
	public boolean isMy() {
		if ((getStorage().getClient().getSecurityProperties().getCertificateChain().length > 0) && (owner != null)) {
			return owner.equals(TreeUtils.parseUser(getStorage().getClient().getSecurityProperties().getCertificateChain()[0].getSubjectDN().getName()));
		}
		return false;
	}
	
}
